<template>
  <div class="common-layout">
    <div class="shell">
      <h2 class="title">{{ isLogin ? 'Login' : 'Register' }}</h2>
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon>
        <el-form-item label="用户名" prop="name">
          <el-input v-model="ruleForm.name" :placeholder="isLogin ? 'Username' : 'New Username'"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" :type="isLogin ? 'password' : 'text'"
                    :placeholder="isLogin ? 'Password' : 'New Password'"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">{{ isLogin ? 'Login' : 'Register' }}</el-button>
        </el-form-item>
      </el-form>
      <div class="footer">

        <button @click="toggleForm">{{ isLogin ? '去注册' : '去登录' }}</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {reactive, ref} from 'vue';
import {ElForm, ElFormItem, ElInput, ElButton,ElMessage} from 'element-plus';
import axios from 'axios';
import router from '@/router';
const ruleFormRef = ref(null);
const ruleForm = reactive({
  name: '',
  password: '',
});
const isLogin = ref(true);
const userlist = ref([]);
const rules = {
  name: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 3, max: 10, message: '长度 3 到 10', trigger: 'blur'},
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 3, max: 8, message: '长度 3 到 8', trigger: 'blur'},
  ],
};
const mounted = () => {
  axios.get('users.json')
      .then(res => {
        userlist.value = res.data.userslist;
      })
      .catch(err => {
        console.error('请求用户数据出现错误：', err);
      });
};
const generateToken = (username) => {
  return username + ':' + Date.now();
};
const submitForm = () => {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      const user = userlist.value.find(u => u.name === ruleForm.name && u.password === ruleForm.password);
      if (isLogin.value && user) {
        sessionStorage.setItem('username', user.name);
        const token = generateToken(user.name);
        sessionStorage.setItem('token', token);
        // 如果有redirect参数，重定向到redirect指定的路径，否则重定向到首页
        let redirectPath;
        if( sessionStorage.getItem("aa") !=="/login"){
            redirectPath = sessionStorage.getItem("aa") || '/';}
        router.push(redirectPath);
        ElMessage({type:"success",message:"登陆成功"})


      } else if (!isLogin.value && !user) {
        // 注册逻辑
        userlist.value.push({ name: ruleForm.name, password: ruleForm.password });
        sessionStorage.setItem('username', ruleForm.name);
        const token = generateToken(ruleForm.name);
        sessionStorage.setItem('token', token);
        alert('注册成功');
        router.push('/');
      } else {
        alert('用户名或密码错误');
      }
    }
  });
};
const toggleForm = () => {
  isLogin.value = !isLogin.value;
  ruleForm.name = '';
  ruleForm.password = '';
};
mounted();
</script>
<style scoped>
.common-layout {
  background: url(../../../public/img/星空.png) no-repeat center;
  width: 100%;
  height: 100vh;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
}

.shell {
  width: 350px;
  padding: 40px;
  display: flex;
  align-items: center;
  flex-direction: column;
  background-color: #ffffff81;
  border-radius: 20px;
  box-shadow: 0 0 30px rgba(0, 0, 0, 0.5);
}

.title {
  font-size: 28px;
  margin-bottom: 20px;
  color: #333;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-input__inner {
  height: 40px;
  border-radius: 20px;
  border: 1px solid #ccc;
}

.el-input__inner:focus {
  border-color: #007bff;
  box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
}

.el-button {
  height: 40px;
  border-radius: 20px;
  background-color: #007bff;
  color: #fff;
}

.el-button:hover {
  background-color: #0056b3;
}

.footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-top: 20px;
}


input[type="checkbox"] {
  width: 20px;
  height: 20px;
  margin-right: 5px;
}

button {
  border: none;
  background: none;
  color: #007bff;
  font-size: 14px;
  cursor: pointer;
}

button {
  border: none;
  background: none;
  color: #007bff;
  font-size: 14px;
  cursor: pointer;
  margin-right: auto;
}
</style>